package proxy.util;

import java.net.InetAddress;
import java.util.List;

public final class MatchUtil {
	
	public static boolean match(String input, String strPattern) {
		boolean ret = false;
		try{
			String ipBlocked = InetAddress.getByName(toHost(strPattern)).getHostAddress();
			String ipCurrentHost = InetAddress.getByName(toHost(input)).getHostAddress();
			if (ipBlocked.equals(ipCurrentHost)) ret = true;
		}catch (Exception e){
		}
		return ret;
	}
	
	public static boolean match(String input, List<String> patterns){
		boolean ret = false;
		for (String strPattern : patterns){
			if (match(input, strPattern)) {
				ret = true;
				break;
			}
		}
		return ret;
	}
	
	private static String toHost(String uri){
		String remoteHost = "";
		int position = -1;
		
		position = uri.indexOf("://");
		if (position != -1){
			remoteHost = uri.substring(position + 3);
		}else{
			remoteHost = uri;
		}
		position = remoteHost.indexOf("/");
		if (position != -1){
			remoteHost = remoteHost.substring(0, position);
		}
		position = remoteHost.indexOf(":");
		if (position != -1){
			remoteHost = remoteHost.substring(0, position);
		}
		return remoteHost;
	}
}
